package domain.game;

import java.awt.Color;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import com.uqbar.vainilla.GameComponent;

import domain.scenes.MainGameScene;
import domain.worm.Worm;

public class BattleManager extends GameComponent<MainGameScene> {

	private int numberOfTeams;
	private List<Team> teams;
	private int currentTeamId;
	private Color[] teamsColors = new Color[4];
	
	
	public BattleManager(int teams){
		this.setNumberOfTeams(teams);
		this.currentTeamId = 0;
		this.initColors();
		this.initTeams();
	}


	private void initColors() {
		this.teamsColors[0] = Color.GREEN;
		this.teamsColors[1] = Color.YELLOW;
		this.teamsColors[2] = Color.RED;
		this.teamsColors[3] = Color.GRAY;
	}


	private void initTeams() {
		this.setTeams(new ArrayList<Team>());
		for (int i = 0; i < this.getNumberOfTeams() ; i++){
			this.getTeams().add(i, new Team(i,this.teamsColors[i]));
		}
		
	}


	public int getCurrentTeamId() {
		return currentTeamId;
	}


	public void setCurrentTeamId(int currentTeam) {
		this.currentTeamId = currentTeam;
	}


	public List<Team> getTeams() {
		return teams;
	}


	public void setTeams(List<Team> teams) {
		this.teams = teams;
	}


	public int getNumberOfTeams() {
		return numberOfTeams;
	}


	public void setNumberOfTeams(int numberOfTeams) {
		this.numberOfTeams = numberOfTeams;
	}
	
	public Team getTeam(int team){
		return this.getTeams().get(team);
	}
	public void addWorm(Worm worm, int team){
		this.getTeam(team).addWorm(worm);
		this.getTeam(team).notifyTeamId();
	}
	public Worm getCurrentWorm(){
		return this.getCurrentTeam().getCurrentWorm();
	}
	public Team getCurrentTeam(){
		return this.getTeams().get(this.getCurrentTeamId());
	}
	
	public void changeTurn(){
		if (!this.isGameOver()){
			this.nextTeam();
		}
		this.getCurrentTeam().nextWorm();
	}


	private void nextTeam() {
		if(this.getCurrentTeamId() + 1 == this.getNumberOfTeams()){
			this.setCurrentTeamId(0);
		}else{
			this.currentTeamId ++;
		}
		if(this.getCurrentTeam().defeated()){
			this.nextTeam();
		}
	}


	public void wormDied(Worm worm) {		
		for(Team team : this.getTeams()){
			team.wormDied(worm);
		}

	}
	public Team winner(){
		Team candidate = null;
		boolean allDefeated = true;
		
		for (Team team : teams){
			if (!team.defeated()){
				candidate = team;
				break;
			}
		}
		for (Team team :teams){
			if (!team.equals(candidate)){
				allDefeated = allDefeated & team.defeated();
			}
		}
		
		if (!allDefeated){
			candidate = null;
		}
		
		return candidate;
	}
	
	public boolean isGameOver(){
		return this.winner() != null;
	}
}
